#region Using

using System;
using System.Net;
using System.Net.Mail;
using WSMon.Core.Configuration;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Mail
{
    public class SmtpChecker : Checker, IChecker
    {
        private readonly string _verificationKey;
        private string _logs = string.Empty;

        public SmtpChecker(EmailAccountConfiguration emailAccount, string verificationKey)
        {
            _verificationKey = verificationKey;
            EmailAccount = emailAccount;
        }

        public EmailAccountConfiguration EmailAccount { get; set; }

        #region IChecker Members

        public bool CheckOut()
        {
            if (EmailAccount == null)
            {
                _logs = "this.EmailAccount can't be null";
                return false;
            }

            try
            {
                var smtpClient = new SmtpClient(EmailAccount.Host, EmailAccount.Port);
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Credentials = new NetworkCredential(EmailAccount.UserName, EmailAccount.Password);
                smtpClient.EnableSsl = EmailAccount.EnableSsl;

                var mailMessage = new MailMessage
                                      {
                                          From = new MailAddress(EmailAccount.Mail, "WebsiteMonitor")
                                      };

                mailMessage.To.Add(EmailAccount.ToMail);
                mailMessage.IsBodyHtml = false;
                mailMessage.Subject = string.Format("Smtp Test Client: [#{0}#]", _verificationKey);
                mailMessage.Body = string.Format("This is a test e-mail message. Verification Key: [#{0}#]",
                                                 _verificationKey);

                smtpClient.Send(mailMessage);

                return true;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}